/*
* FileUp.java
* Created on  2014-4-25 下午6:04
* 版本       修改时间          作者      修改内容
* V1.0.1    2014-4-25       gaoxinyu    初始版本
*
*/
package com.genghis.ptas.util;

import com.genghis.ptas.constant.DictConstant;
import com.genghis.ptas.course.entity.ChapterInfo;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.*;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * 类的描述信息
 *
 * @author fengxuanzhen
 * @version 1.0.1
 */
public class FileUp {
    public static void uploadFile(InputStream input, String filePath, String fileName) {
        try {
            FileOutputStream os = new FileOutputStream(filePath + fileName);
            byte[] bytes = new byte[1024];
            int c;
            while ((c = input.read(bytes)) != -1) {
                os.write(bytes, 0, c);
            }
            os.close();
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    public String upPhoto(HttpServletRequest request, String img) throws ServletException, IOException {
        String photoUrl = DateUtil.getSystemDate("yyyyMMDDHHSS");
        String path = request.getSession().getServletContext().getRealPath("/" + DictConstant.USER_PHOTO_ROOT_URL + "/");
        String photoImgPath = path + "/";
        File file = new File(photoImgPath);
        file.mkdirs();
        MultipartFile photo = ((MultipartHttpServletRequest) request).getFile(img);
        InputStream input = photo.getInputStream();
        uploadFile(input, photoImgPath, photoUrl + DictConstant.PHOTO_IMG);
        String photoPath = photoImgPath + photoUrl + DictConstant.PHOTO_IMG;
        photoPath = photoPath.substring(photoPath.indexOf(DictConstant.USER_PHOTO_ROOT_URL));
        return photoPath;
     }


    public static InputStream getInputStream(MultipartHttpServletRequest request, String photoId) throws IOException {
        MultipartFile file = request.getFile(photoId);
        return file.getInputStream();
    }

    public String[] upScorm(HttpServletRequest request, String scormPath, String upFile, String img) throws ServletException, IOException {
        String imgUrl = DateUtil.getSystemDate("yyyyMMDDHHSS");
        String path = request.getSession().getServletContext().getRealPath("/" + DictConstant.TOP_SCORM_FILE_NAME + "/");
        String scormImgPath = path + "/" + scormPath + "/";
        String scormFilePath = path + "/" + scormPath + "/" + DictConstant.SCORM_FILE_NAME + "/";
        //创建文件，防文件夹不存在
        File file = new File(scormFilePath);
        file.mkdirs();
        //接受页面流文件
        InputStream input = getInputStream((MultipartHttpServletRequest) request, upFile);
        uploadFile(input, scormFilePath, DictConstant.SCORM_NAME);
        input = getInputStream((MultipartHttpServletRequest) request, img);
        uploadFile(input, scormImgPath, imgUrl + DictConstant.SCORM_IMG);
        //返回路径 0图片引用路径 1文件路径
        String scormFile[] = {"", ""};
        scormFile[0] = scormImgPath + imgUrl + DictConstant.SCORM_IMG;
        scormFile[0] = scormFile[0].substring(scormFile[0].indexOf(DictConstant.SCORM_FILE_NAME));
        scormFile[1] = scormFilePath;
        unzip(scormFile[1] + DictConstant.SCORM_NAME);
        return scormFile;
    }

    public void unzip(String fileName) {
        try {
            String filePath = fileName.substring(0, fileName.lastIndexOf("/") + 1);
            ZipFile zipFile = new ZipFile(fileName);
            Enumeration emu = zipFile.entries();
            while (emu.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) emu.nextElement();
                if (entry.isDirectory()) {
                    new File(filePath + entry.getName()).mkdirs();
                    continue;
                }
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
                File file = new File(filePath + entry.getName());
                File parent = file.getParentFile();
                if (parent != null && (!parent.exists())) {
                    parent.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(file);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                int count;
                byte data[] = new byte[1024];
                while ((count = bis.read(data, 0, 1024)) != -1) {
                    bos.write(data, 0, count);
                }
                bos.flush();
                bos.close();
                bis.close();
            }
            zipFile.close();
        } catch (Exception e) {
        }
    }

    public List<ChapterInfo> analyzeXml(String url) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        //得到一个Xpath对象
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expression = xpath.compile("/manifest/organizations/organization");
        //得到一个输入对象
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(new File(url));
        NodeList nodeChapterList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
        //获得课件章路径
        String scoPath = url.substring(url.indexOf(DictConstant.TOP_SCORM_FILE_NAME));
        url = scoPath.substring(0, scoPath.indexOf(DictConstant.IMSMANIFEST));
        List<ChapterInfo> xmalInfos = new LinkedList<ChapterInfo>();
        for (int i = 0; i < nodeChapterList.getLength(); i++) {
            Element element = (Element) nodeChapterList.item(i);
            //获取课件章信息
            ChapterInfo xmalInfo = new ChapterInfo();
            xmalInfo.setXmlChapterId(element.getAttribute("identifier"));
            NodeList nodeList = element.getElementsByTagName("title");
            if (!nodeList.item(0).getTextContent().equals("") && nodeList.item(0).getTextContent() != null) {
                xmalInfo.setChapterName(nodeList.item(0).getTextContent());
            }
            xmalInfo.setChapterType(element.getTagName());
            xmalInfo.setParentId("0");
            xmalInfo.setChapterUrl("");
            xmalInfos.add(xmalInfo);
            //获得课件节路径
            getElement(element, xmalInfos, url, document);
        }
        return xmalInfos;
    }

    private void getElement(Element element, List<ChapterInfo> xmalInfos, String url, Document document) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            if (nodes.item(i).getNodeName().equals("item")) {
                getElement((Element) nodes.item(i), xmalInfos, url, document);
                Element element1 = (Element) nodes.item(i);
                ChapterInfo xmalInfo = new ChapterInfo();
                NodeList nodeList = element1.getElementsByTagName("title");
                if (!nodeList.item(0).getTextContent().equals("") && nodeList.item(0).getTextContent() != null) {
                    xmalInfo.setChapterName(nodeList.item(0).getTextContent());
                }
                xmalInfo.setChapterType(element1.getTagName());
                xmalInfo.setParentId(element.getAttribute("identifier"));
                xmalInfo.setXmlChapterId(element1.getAttribute("identifier"));
                if (!element1.getAttribute("identifierref").equals("") && element1.getAttribute("identifierref") != null) {
                    xmalInfo.setChapterUrl(url + getUrl(element1.getAttribute("identifierref"), document));
                }
                xmalInfos.add(xmalInfo);
            }
        }
    }

    //获取路径
    private String getUrl(String identifier, Document document) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        //得到一个Xpath对象
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expression = xpath.compile("/manifest/resources/resource[@identifier='" + identifier + "']");
        //得到一个输入对象
        Element element = (Element) expression.evaluate(document, XPathConstants.NODE);
        //获取路径
        return element.getAttribute("href");
    }

    //修改图片路径
    public String url(HttpServletRequest request, String scormPath, String img) throws ServletException, IOException {
        String prefix = DateUtil.getSystemDate("yyyyMMDDHHSS");
        String path = request.getSession().getServletContext().getRealPath("/" + DictConstant.TOP_SCORM_FILE_NAME + "/");
        String scormImgPath = path + "/" + scormPath + "/";
        //接受页面流文件
        InputStream input = getInputStream((MultipartHttpServletRequest) request, img);
        uploadFile(input, scormImgPath, prefix + DictConstant.SCORM_IMG);
        //返回图片路径
        String imgFile = scormImgPath + prefix + DictConstant.SCORM_IMG;
        imgFile = imgFile.substring(imgFile.indexOf(DictConstant.TOP_SCORM_FILE_NAME));
        return imgFile;
    }
}
